<template>
  <div class="system-customer">
    <div class="btn-wrap">
      <el-button
        type="primary"
        style="padding: 8px 22px;border-radius:2px;background-color: #0066F9;border-radius: 4px;"
        @click="createField"
      >
        <i class="el-field"></i>
        新建字段</el-button
      >
      <el-button
        type="primary"
        style="padding: 8px 22px;border-radius:2px;background-color:#E0EDFF;border:border: 1px solid #0066F9;color:#0066F9;border-radius: 4px;"
        @click="fieldAllocation"
      >
        <i class="el-allocation"></i>
        字段分配</el-button
      >
    </div>
    <el-tabs v-model="acitveTabValue" @tab-click="tabClick">
      <el-tab-pane
        :label="item.name"
        :name="`${item.label}`"
        v-for="(item, index) in tableList"
        :key="index"
      >
        <div class="customer-content">
          <el-table
            v-loading="loading"
            :data="tabData"
            :height="`calc(100vh - 200px)`"
            highlight-current-row
            tooltip-effect="dark popper_sty"
          >
            <el-table-column
              prop="name"
              label="字段名称"
              show-overflow-tooltip
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column
              prop="formType"
              label="字段类型"
              show-overflow-tooltip
              align="center"
              width="100"
            >
              <span slot-scope="scope">{{
                getFormType(scope.row.formType)
              }}</span>
            </el-table-column>
            <el-table-column
              prop="deptNames"
              label="部门权限"
              show-overflow-tooltip
              align="center"
            >
              <span slot-scope="scope">{{
                scope.row.deptNames
                  ? scope.row.deptNames.split(",").join("， ")
                  : "全部"
              }}</span>
            </el-table-column>
            <el-table-column
              prop="roleNames"
              label="角色权限"
              show-overflow-tooltip
              align="center"
            >
              <span slot-scope="scope">
                {{
                  scope.row.roleNames
                    ? scope.row.roleNames.split(",").join("， ")
                    : "全部"
                }}
              </span>
            </el-table-column>
            <el-table-column
              prop="isNull"
              label="必填"
              show-overflow-tooltip
              align="center"
              width="100"
            >
              <el-switch
                slot-scope="scope"
                @change="hiddenChange(scope.row, 'isNull')"
                v-model="scope.row.isNull"
                active-color="#2362FB"
                inactive-color="#dcdfe6"
                :active-value="1"
                :inactive-value="0"
                :disabled="
                  scope.row.operateType == 1 || scope.row.operateType == 3
                "
              >
              </el-switch>
            </el-table-column>
            <el-table-column
              prop="isHidden"
              label="隐藏"
              show-overflow-tooltip
              align="center"
              width="100"
            >
              <el-switch
                slot-scope="scope"
                @change="hiddenChange(scope.row, 'isHidden')"
                v-model="scope.row.isHidden"
                active-color="#2362FB"
                inactive-color="#dcdfe6"
                :active-value="1"
                :inactive-value="0"
                :disabled="
                  scope.row.operateType == 1 || scope.row.operateType == 2
                "
              >
              </el-switch>
            </el-table-column>

            <el-table-column
              prop="checkOkEdit"
              label="全局编辑"
              show-overflow-tooltip
              align="center"
              width="100"
              v-if="acitveTabValue == 25"
            >
              <el-switch
                slot-scope="scope"
                @change="hiddenChange(scope.row, 'checkOkEdit')"
                v-model="scope.row.checkOkEdit"
                active-color="#2362FB"
                inactive-color="#dcdfe6"
                :active-value="1"
                :inactive-value="0"
                :disabled="scope.row.allEditType == 1"
              >
              </el-switch>
            </el-table-column>

            <el-table-column
              prop="relevant"
              label="继承"
              show-overflow-tooltip
              align="center"
              width="100"
            >
              <span slot-scope="scope">{{
                scope.row.fieldType == 1
                  ? "系统默认"
                  : scope.row.relevant
                  ? "已继承"
                  : "无继承"
              }}</span>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  v-if="
                    scope.row.fieldType != 1 &&
                      [1, 2, 6].includes(scope.row.label)
                  "
                  @click="handleCustomField('inherit', scope.row, scope.$index)"
                  >继承字段</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleCustomField('edit', scope.row, scope.$index)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  v-if="scope.row.fieldType != 1"
                  @click="handleCustomField('del', scope.row, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="字段继承"
      :visible.sync="inheritShow"
      :close-on-click-modal="false"
      width="420px"
      @close="inheritClose"
    >
      <el-form
        label-position="top"
        label-width="80px"
        :model="formInherit"
        ref="formInherit"
        :rules="rules"
      >
        <el-form-item label="字段名称" prop="label">
          <el-input v-model="formInherit.labelName" disabled></el-input>
        </el-form-item>
        <el-form-item label="字段类型" prop="extendType">
          <el-radio-group v-model="formInherit.extendType">
            <el-radio :label="0">原有字段</el-radio>
            <el-radio :label="1">新建字段</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formInherit.extendType === 0">
          <el-form-item label="继承字段" prop="extendFieldId">
            <el-select
              v-model="formInherit.extendFieldId"
              placeholder="请选择"
              @change="extendChange"
            >
              <el-option
                v-for="item in inheritData"
                :key="item.fieldId"
                :label="item.name"
                :value="item.fieldId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-if="formInherit.extendType === 1">
          <el-form-item label="字段名称">
            <el-input v-model="formInherit.name"></el-input>
          </el-form-item>
          <el-form-item label="部门权限">
            <el-input
              v-model="formInherit.deptNames"
              disabled
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色权限">
            <el-input
              v-model="formInherit.roleNames"
              disabled
              type="textarea"
            ></el-input>
          </el-form-item>
        </template>
        <div class="flooter d-flex justify-content-end">
          <el-button @click="inheritClose">取消</el-button>
          <el-button type="primary" @click="InheritSubmit">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  customFieldIndexAPI,
  customFieldListAPI,
  crmSettingFieldInherit,
  customInheritListAPI,
  fieldDelField,
  customFieldHandleAPI
} from "@/api/admin/crm";
import FieldList from "../model/fieldList";

export default {
  name: "CustomField",

  components: {},
  data() {
    return {
      loading: false,
      // 自定义字段设置
      tableList: [],
      // 展示表单预览
      tablePreviewData: { types: "", typesId: "" },
      showTablePreview: false,
      inheritShow: false, // 继承字段弹框
      acitveTabValue: "", // 选择tab下标
      tabData: [], // tab数据
      inheritData: [], // 继承字段数据
      formInherit: {
        label: "", // 字段名称
        extendType: 0, // 字段类型
        name: "", // 继承字段
        labelName: "", // 继承字段名称
        roleNames: "", // 角色权限
        deptNames: "" // 部门权限
      }, // 继承字段
      rules: {
        label: {
          required: true,
          message: "请输入",
          trigger: "blur"
        },
        extendType: {
          required: true,
          message: "请选择",
          trigger: "blur"
        }
      }
    };
  },
  created() {
    this.getDetail();
  },
  methods: {
    /**
     * 详情
     */
    getDetail() {
      this.loading = true;
      customFieldIndexAPI()
        .then(res => {
          this.tableList = res.data;
          this.acitveTabValue = res.data[0].label + "";
          // 获取初始化第一项的值
          this.tabClick();
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 列表的编辑 删除 继承字段
     */
    handleCustomField(type, item, index) {
      this.tablePreviewData = item;
      // 编辑
      if (type == "edit") {
        this.$router.push({
          name: "handlefieldEdit",
          params: {
            type: {
              1: "crm_leads",
              2: "crm_customer",
              3: "crm_contacts",
              4: "crm_product",
              5: "crm_business",
              6: "crm_contract",
              7: "crm_receivables",
              17: "crm_visit"
            }[item.label],
            id: "none",
            label: item.label, // 获取指定配置字段的id
            index, // 用于获取编辑字段的下标
            formType: item.formType // 标签类型
          }
        });
      } else if (type == "del") {
        fieldDelField({
          label: item.label,
          fieldId: item.fieldId
        }).then(res => {
          console.log(res);
          this.$message.success("删除成功");
          this.tabClick();
        });
        // 删除
      } else if (type == "inherit") {
        const label =
          item.label == 1 ? 2 : item.label == 2 ? 6 : item.label == 6 ? 7 : 29;
        customInheritListAPI({ label }).then(res => {
          // 继承字段
          this.inheritShow = true; // 继承字段弹框
          this.formInherit.label = item.label; // 字段名称
          this.formInherit.labelName = item.name; // 字段名称
          this.formInherit.fieldId = item.fieldId; // 字段id
          this.formInherit.roleNames = item.roleNames; // 角色权限
          this.formInherit.deptNames = item.deptNames ? item.deptNames : "全部"; // 部门权限
          this.formInherit.type = item.type; // 字段类型
          this.inheritData = res.data.filter(it => it.type == item.type); // 继承字段数据
        });
      }
    },

    // 继承字段更改
    extendChange(e) {
      this.inheritData.forEach(item => {
        if (item.fieldId == e) {
          this.formInherit.extendFieldId = item.fieldId;
        }
      });
    },

    // 新建字段
    createField() {
      this.$router.push({
        name: "handlefield",
        params: {
          type: {
            1: "crm_leads",
            2: "crm_customer",
            3: "crm_contacts",
            4: "crm_product",
            5: "crm_business",
            6: "crm_contract",
            7: "crm_receivables",
            17: "crm_visit"
          }[this.acitveTabValue],
          id: "none",
          label: this.acitveTabValue
        }
      });
    },

    // 字段分配
    fieldAllocation() {
      this.$router.push({
        name: "handleAllocation",
        params: {
          label: this.acitveTabValue
        }
      });
    },

    /**
     * tab切换
     */
    tabClick() {
      this.loading = true;
      customFieldListAPI(
        { label: this.acitveTabValue },
        { isQueryFieldType: false }
      )
        .then(res => {
          this.tabData = res.data;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 过去字段类型
    getFormType(type) {
      for (let i = 0; i < FieldList.length; i++) {
        if (FieldList[i].formType == type) {
          return FieldList[i].name;
        }
      }
    },
    // 继承字段保存
    InheritSubmit() {
      this.$refs["formInherit"].validate(valid => {
        if (valid) {
          // if (this.formInherit.type != this.formInherit.extendType) {
          //   this.$message({
          //     type: "error",
          //     message: "字段类型不一致"
          //   });
          //   return;
          // }
          const options = {
            label: this.formInherit.label + "",
            fieldId: this.formInherit.fieldId,
            extendFieldId: this.formInherit.extendFieldId,
            name: this.formInherit.name + "",
            extendType: this.formInherit.extendType
          };
          crmSettingFieldInherit(options).then(res => {
            this.$message({
              type: "success",
              message: "继承成功!"
            });
            this.inheritClose();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 继承字段取消
    inheritClose() {
      this.inheritShow = false;
      this.formInherit = {
        label: "", // 字段名称
        extendType: 0, // 字段类型
        name: "", // 继承字段
        labelName: "", // 继承字段名称
        roleNames: "", // 角色权限
        deptNames: "" // 部门权限
      };
    },

    // 隐藏更改
    hiddenChange(row, type) {
      const text =
        type == "isNull"
          ? row.isNull == 1
            ? "必填"
            : "非必填"
          : type == "isHidden"
          ? row.isHidden == 1
            ? "显示"
            : "隐藏"
          : type == "checkOkEdit"
          ? row.checkOkEdit == 1
            ? "可编辑"
            : "不可编辑"
          : "";
      this.$confirm(
        '确认要修改"' + row.name + '"字段为' + text + "吗？",
        "提示",
        {
          type: "warning"
        }
      )
        .then(() => {
          customFieldHandleAPI({
            data: this.tabData,
            label: this.acitveTabValue
          })
            .then(res => {
              if (res.code == 0) {
                this.$message.success("操作成功");
              }
            })
            .finally(() => {
              this.tabClick();
            });
        })
        .catch(function() {
          type == "isHidden"
            ? (row.isHidden = row.isHidden == 1 ? 0 : 1)
            : type == "isNull"
            ? (row.isNull = row.isNull == 1 ? 0 : 1)
            : type == "checkOkEdit"
            ? (row.checkOkEdit = row.checkOkEdit == 1 ? 0 : 1)
            : "";
        });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.system-customer {
  height: 100%;
  background-color: #fff;
  padding: 20px;
  position: relative;
}
.btn-wrap {
  position: absolute;
  right: 20px;
  z-index: 2;
}
::v-deep .el-field {
  display: inline-block;
  background: url("../../../../assets/img/crm/field.png") center no-repeat;
  background-size: cover;
  width: 16px;
}
::v-deep .el-field:before {
  content: "1";
  color: transparent;
}

::v-deep .el-allocation {
  display: inline-block;
  background: url("../../../../assets/img/crm/allocation.png") center no-repeat;
  background-size: cover;
  width: 16px;
}
::v-deep .el-allocation:before {
  content: "1";
  color: transparent;
}
/deep/ .customer-content {
  border-bottom: 1px solid $xr-border-line-color;
  .el-table th.el-table__cell.is-leaf {
    border: none;
    .cell {
      color: #999;
    }
  }
}

.table-item-label {
  vertical-align: middle;
}
.table-item-icon {
  width: 30px;
  height: 30px;
  margin-right: 8px;
  vertical-align: middle;
  border-radius: 4px;
}

.table-item-time {
  color: #999;
}

.el-table {
  /deep/ .el-table__body td {
    height: 60px;
  }
}

.el-tabs {
  /deep/ .el-tabs__nav-wrap::after {
    background-color: #ebebeb;
    height: 1px;
  }
}

.el-form {
  /deep/ .el-form-item__label {
    height: 30px;
    line-height: 30px;
    padding: 0;
  }
}

/deep/ .el-dialog__title {
  color: #000;
  font-weight: bold !important;
}

/deep/ .el-dialog__body {
  padding: 0px;
  background-color: #f7f8fa;
  .el-form-item {
    margin: 0;
    padding: 0 20px 15px;
    background-color: #fff;
  }

  .flooter {
    border-top: 1px solid #dedede;
    padding: 10px 15px 10px 0;
  }
}
</style>

<style>
/* .el-tooltip__popper {
  width: 400px;
} */
</style>
